#pragma once
#include <vector>
#include <queue>
#include <pthread.h>
#include "Task.hpp"
extern Log lg;


static const int defaultnumber = 5;

struct ThreadData
{
    std::string _threadname;
    pthread_t tid;
};

template <typename T>
class ThreadPool
{
private:
    void Lock()
    {
        pthread_mutex_lock(&_mutex);
    }
    void Unlock()
    {
        pthread_mutex_unlock(&_mutex);
    }
    void WakeUp()
    {
        pthread_cond_signal(&_cond);
    }
    void ThreadSleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }
    std::string GetThreadName(pthread_t tid)
    {
        for (const auto &th : _thread)
        {
            if (tid == th.tid)
                return th._threadname;
        }

        return "NoName";
    }
    bool IsQueueEmpty()
    {
        return _task.empty();
    }

public:
    static void *HandlerTask(void *args)
    {
        ThreadPool<T> *tp = static_cast<ThreadPool<T> *>(args);
        std::string name = tp->GetThreadName(pthread_self());
        while (true)
        {
            // 加锁
            tp->Lock();
            while (tp->IsQueueEmpty())
            {
                tp->ThreadSleep();
            }
            T t = tp->pop();
            // 解锁
            tp->Unlock();

            t.run();

        }
    }
    // 线程启动
    void start()
    {
        int num = _thread.size();
        for (int i = 0; i < num; i++)
        {
            _thread[i]._threadname = "Thread-" + std::to_string(i);
            pthread_create(&(_thread[i].tid), nullptr, HandlerTask, this);
        }
    }
    // 消费任务
    T pop()
    {
        T t = _task.front();
        _task.pop();
        return t;
    }
    // 生产任务
    void push(const T &in)
    {
        Lock();
        _task.push(in);
        // 唤醒
        WakeUp();
        Unlock();
    }

    static ThreadPool<T> *GetInstance()
    {
        if (nullptr == tp_)
        {
            pthread_mutex_lock(&lock_);
            if (nullptr == tp_)
            {
                std::cout << "log: singleton create done first!" << std::endl;
                tp_ = new ThreadPool<T>();
            }
            pthread_mutex_unlock(&lock_);
        }

        return tp_;
    }

private:
    ThreadPool(int num = defaultnumber)
        : _thread(num)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }
    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

    ThreadPool(const ThreadPool<T> &) = delete;
    const ThreadPool<T> &operator=(const ThreadPool<T> &) = delete;

    static ThreadPool<T> *tp_;
    static pthread_mutex_t lock_;

    // 线程
    std::vector<ThreadData> _thread;
    // 任务队列
    std::queue<T> _task;
    // 互斥锁
    pthread_mutex_t _mutex;
    // 条件变量
    pthread_cond_t _cond;
};

template <class T>
ThreadPool<T> *ThreadPool<T>::tp_ = nullptr;

template <class T>
pthread_mutex_t ThreadPool<T>::lock_ = PTHREAD_MUTEX_INITIALIZER;